/* =========================================================
 * acp.component.magnifier.js
 * =========================================================
 * 输入放大镜
 * Copyright(c) 1998 - 2016 YGSoft.Inc, All Rights Reserved
 * Created by wugang5 on 2016/3/7.
 * ========================================================= */

define(["jquery"],function($){
	(function($){
    /**
     * 构造放大镜
     */
    var Magnifier = function (element, options) {
        this.$element = $(element);
        this.size = options.size;
        this.position = options.position;
        this.separator = options.separator;
        this.myStyle = options.myStyle;
        this.minLen = options.minLen;
        this.maxLen = options.maxLen;
        //原始比例
        this.fontZoom = 30/21;
        this.init();
    };

    Magnifier.prototype = {
        construct : Magnifier,
        /**
         * 初始化放大镜
         */
        init : function (){
            var divMagnifier = "<div class='magnifier'></div>";
            var $element = this.$element;
            var me = this;
            //生成div
            $element.after(divMagnifier);
            this.$magnifier = $element.next(".magnifier");
            //设置放大镜位置
            this.setPosition(this.position);
            //设置当前元素的maxLength属性
            if (this.maxLen) {
                $element.attr("maxLength",this.maxLen);
            }
            //设置当前元素的minLength属性
            if (this.minLen) {
                $element.attr("minLength",this.minLen);
            }
            if (this.myStyle) {
                this.$magnifier.addClass(this.myStyle);
            }
            //绑定事件
            $element.off("keyup focus").on("keyup focus", function(){
                var $magnifier = me.$magnifier,
                    inputVal = $.trim(me.$element.val());
                //不显示放大镜
                if (inputVal === "") {
                    $magnifier.css("display","none");
                    return;
                }
                //获取分隔规则
                if (me.separator){
                    var rule = me.separator.rule;
                    var sign =me.separator.sign;
                    inputVal = splitInputerValue(inputVal ,rule, sign);
                }
                $magnifier.css("display","block");
                $magnifier.text(inputVal);
                $magnifier.fadeIn("fast");
            });
            $element.off("blur").on("blur", function(){
                //隐藏并置空
                var $magnifier = me.$magnifier;
                $magnifier.css("display","none");
                $magnifier.text("");
                $magnifier.fadeOut("fast");
            });

        },
        /**
         * 设置放大镜字体大小
         */
        setSize : function (size) {
            this.size = size;
            this.$magnifier.css("font-size", size);
            //字体大小修改后要重新设置位置
            this.setPosition(this.position);
        },
        /**
         * 设置放大镜位置
         */
        setPosition : function (position) {
            var $element = this.$element,
            	$magnifier = this.$magnifier,
            	parentPos = $element.offsetParent().offset(),
                inputPos = $element.offset(),
                left = inputPos.left - parentPos.left,
                top;
            if (position === 'bottom'){
                top = inputPos.top - parentPos.top + $element[0].offsetHeight;
            } else if (position === "top"){
                if (this.size == 21) {
                    //默认字体大小时  padding:20
                    top = inputPos.top - parentPos.top - 50;
                } else {
                    top = inputPos.top - parentPos.top - 20 - this.fontZoom * this.size;
                }
            }
            $magnifier.css({top: top, left: left});
            this.position = position;
        },
        /**
         *设置放大镜显示内容的分隔规则
         */
        setSeparator : function (separator) {
            this.separator = separator;
        },
        /**
         *设置放大镜样式
         */
        setMStyle : function (style) {
            this.myStyle = style;
            this.$magnifier.addClass(style);
        },
        /**
         *设置当前元素的maxLength或者minLength属性
         */
        setInputLen : function (){
            var limit = Array.prototype.slice.call(arguments);
            var len = limit.length;
            if (len ===1 ){
                this.maxLen  = limit[0];
                this.$element.attr("maxLength",limit[0]);
            } else if (len === 2) {
                var max = limit[0], min = limit[1], temp;
                if ( max < min) {
                    temp = max;
                    max = min;
                    min = temp;
                }
                this.maxLen = max;
                this.minLen = min;
                this.$element.attr("maxLength",max);
                this.$element.attr("minLength",min);
            }

        }
    };
    
    /**
     *分隔字符串
     *@example
     splitInputerValue("18507091839") "18507091839"
     splitInputerValue("18507091839",2)  "18 50 70 91 83 9"
     splitInputerValue("18507091839",[3],"-")  "185-070-918-39"
     splitInputerValue("18507091839",[3,4,4],"*") "185*0709*1839"
     splitInputerValue("18507091839",[2,3]) "18 507 091839"
     *@param {string} inputVal 需要改造的字符串
     *@param {number | Array} rule 分隔规则，可以为单个数字，或数值型的数组；可选
     *@param {string} sign 分隔符 如"-","*" ，可选，默认以空格分隔
     *@return {string} 改造后的字符串
     */
    function splitInputerValue(inputVal ,rule ,sign){
        if (typeof rule === "number"){
            //以指定的单个数字分隔
            return _singleSplit( inputVal, rule, sign);
        } else if( rule && $.isArray(rule)){
            var inputLen = inputVal.length;
            var j = rule.length;
            var hasRest = true;
            var array = [];
            var n = 0;
            if ( j == 1) {
                //数组只有一个元素时按单个数字分隔 如[2]
                return _singleSplit(inputVal, rule[0], sign);
            } else {
                //以如[3,4,4]切割
                for (var i = 0; i < j; i++){
                    array.push(inputVal.substr(n,rule[i]));
                    n += rule[i];
                    //如果n大于inputLen，说明字符已经分隔完成
                    if( n >= inputLen ){
                        hasRest = false;
                        break;
                    }
                }
                //如果字符分隔未完成，把剩下的装入
                if (hasRest){
                    array.push(inputVal.substring(n));
                }
                //组装
                return _splitWithSign(array, sign);
            }
        } else{
            //没有分隔规则直接返回，不处理
            return inputVal;
        }
    }

    /**
     *分隔字符串
     *@param {string} targetStr 目标字符串
     *@param {number} baseNumber 分隔数：如每N个分隔一次
     *@param {string} sign 分隔符 如"-","*"
     *@return {string} 分隔后的字符串
     */
    function _singleSplit(targetStr, baseNumber, sign){
        var n = 0;
        var array = [];
        //分隔数不能为0
        if ( baseNumber !== 0){
            while ( n < targetStr.length ){
                array.push(targetStr.substr(n,baseNumber));
                n += baseNumber;
            }
            return _splitWithSign(array, sign);
        } else {
            return targetStr;
        }
    }

    /**
     *拼接数组
     *@param {Array} array 目标数组
     *@param {string} sign 分隔符 如"-","*"
     *@return {string} 拼接后的字符串
     */
    function _splitWithSign(array, sign) {
        var result;
        if(sign && typeof sign == 'string'){
            result = array.join(sign);
        } else {
            //没有分隔符默认用空格分开
            result = array.join(" ");
        }
        //返回拼接后的结果
        return result;
    }

    $.fn.magnifier = function (option, args) {
        return this.each(function () {
            var $this = $(this),
                data = $this.data('magnifier'),
                //合并options
                options = $.extend({}, $.fn.magnifier.defaults, $this.data(), typeof option == 'object' && option);

            if (!data) {
            	$this.data('magnifier', (data = new Magnifier(this, options)));
            }
            if (typeof option == 'string') data[option].apply(data, [].concat(args));
        });
    };

    //放大镜默认选项
    $.fn.magnifier.defaults = {
        size : 21,
        position : "top",
        separator : null,
        myStyle : null,
        minLen : null,
        maxLen: null
    };

    $.fn.magnifier.Constructor = Magnifier;


	})(window.jQuery);
	
});
